package com.maserb.monitor.wechat;

import com.maserb.monitor.common.AjaxResult;
import com.maserb.monitor.common.AjaxUtils;
import com.maserb.monitor.common.Func_T;
import com.maserb.monitor.entity.UserEntity;
import com.maserb.monitor.entity.card.RechargeRecordEntity;
import com.maserb.monitor.entity.schoolStudent.SchoolStudentEntity;
import com.maserb.monitor.repository.schoolStudent.RechargeRecordRepository;
import com.maserb.monitor.service.author_manage.UserService;
import com.maserb.monitor.service.remote.EcCardService;
import com.maserb.monitor.service.schoolStudent.SchoolStudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

@Slf4j
@Controller
@RequestMapping("/weChatPay")
public class WeChatPayController {

    @Autowired
    private RechargeRecordRepository rechargeRecordRepository;

    @Autowired
    private SchoolStudentService schoolStudentService;

    @Autowired
    private WeChatPayRequest weChatPayRequest;

    @Autowired
    private EcCardService ecCardService;

    @Autowired
    private UserService userService;


    /**
     *
     * @param request
     * @param studentId 人员id
     * @param type 人员类型 1：学生 2：老师
     * @param totalAmount 充值金额
     * @return
     */
    @RequestMapping("/pay")
    @ResponseBody
    public AjaxResult<WxPay> prePay(HttpServletRequest request, String studentId, String type, Double totalAmount) {
        return AjaxUtils.process(new Func_T<WxPay>() {
            @Override
            public WxPay invoke() throws Exception {
                WxPay result = new WxPay();

                //交易金额
                if (totalAmount == null || totalAmount < 0) {
                    result.setCode("401");
                    result.setMsg("交易金额错误");
                    return result;
                }

                RechargeRecordEntity recharge = new RechargeRecordEntity();

                if(StringUtils.isEmpty(type) || type.equals("1")) {
                    SchoolStudentEntity student = schoolStudentService.findOne(studentId);
                    recharge.setStudent(student);
                    recharge.setCardNumber(student.getCardNumber());
                } else {
                    UserEntity teacher = userService.findOne(studentId);
                    recharge.setTeacher(teacher);
                    recharge.setCardNumber(teacher.getCardNumber());
                }
                recharge.setCreateTime(new Date());
                recharge.setTotalAmount(totalAmount);
                recharge.setPayStatus("0"); //未支付
                recharge.setRemarks("微信充值");
                rechargeRecordRepository.save(recharge);

                //商品描述
                String detail = "{'orderId:'" + recharge.getId() + ",'money':" + totalAmount + "}";
                String description = "一卡通充值";
                //IP地址
                String ipStr = request.getRemoteAddr();
                //提交请求获取交易流水号
                Map<String, String> rst = weChatPayRequest.requestOrderFlow(recharge.getId().toString(), "1", new BigDecimal(totalAmount), description, detail, ipStr);
                if (rst != null && rst.get("return_code") != null && "SUCCESS".equals(rst.get("return_code").toString()) && rst.get("prepay_id") != null) {
                    //根据流水号生成支付签名
                    Map<String, Object> signMap = weChatPayRequest.getPaySignParams(rst.get("prepay_id").toString());
                    if (signMap == null) {
                        result.setCode("705");
                        result.setMsg("获取支付签名失败");
                        return result;
                    } else {
                        //返回签名信息
                        result.setCode("200");
                        result.setTradeNo(recharge.getId());
                        result.setWxSign(signMap);
                    }
                } else {
                    StringBuilder errorMsg = new StringBuilder("获取交易流水号失败");
                    if (rst == null) {
                        errorMsg.append("(null flow result)");
                    } else {
                        errorMsg.append("[").append(rst.get("return_msg")).append(":").append(rst.get("return_code")).append("]");
                    }

                    result.setMsg(errorMsg.toString());
                    result.setCode("706");
                }
                return result;
            }
        });
    }


    @RequestMapping("/notify")
    @ResponseBody
    public String notify(final HttpServletRequest request) throws Exception {
        log.info("=====订单支付回调成功=====");
        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        String resultXml = new String(outSteam.toByteArray(), "utf-8");
        Map<String, String> params = weChatPayRequest.doXMLParse(resultXml);
        outSteam.close();
        inStream.close();

        SortedMap<String,Object> return_data = new TreeMap<String,Object>();
        if (!weChatPayRequest.isTenpaySign("UTF-8", params)) {
            // 支付失败
            log.info("=====支付失败=====");
            return_data.put("return_code", "FAIL");
            return_data.put("return_msg", "return_code不正确");
        } else {
            String orderId = params.get("out_trade_no");
            if (StringUtils.isEmpty(orderId)) {
                // 支付失败
                log.info("=====支付失败：获取订单id失败=====");
                return_data.put("return_code", "FAIL");
                return_data.put("return_msg", "return_code不正确");
            } else {
                log.info("=====订单id：" + orderId);
                orderId = weChatPayRequest.regetTradeNo(orderId);
                RechargeRecordEntity recharge = rechargeRecordRepository.findById(orderId).get();
                if(recharge != null) {
                    recharge.setPayStatus("1");
                    rechargeRecordRepository.save(recharge);

                    ecCardService.doAddRechargeRecord(recharge);

                    return_data.put("return_code", "SUCCESS");
                    return_data.put("return_msg", "OK");
                } else {
                    // 支付失败
                    log.info("=====支付失败：订单不存在=====");
                    return_data.put("return_code", "FAIL");
                    return_data.put("return_msg", "订单不存在");
                }
            }
        }

        return weChatPayRequest.getRequestXml(return_data);
    }
}
